package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.cloudbroker.bcs.common.constants.BasicErrorCodes;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.model.Pagination;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.InterestDetailForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.InterestDetailVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.UserEntityVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.ask.AskBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.ask.back.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.ask.vo.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.leader.back.LeaderBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.back.UsersQueryVo;
import com.cloudbroker.bcs.platform.ltb.middle.entity.*;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.AskParam;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.AskView;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.LeaderAskParam;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.lightinvesting.LightinvestingService;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.usercenter.UserCenterService;
import com.cloudbroker.bcs.platform.ltb.middle.service.*;
import com.cloudbroker.bcs.platform.ltb.middle.util.AskCacheUtil;
import com.cloudbroker.bcs.platform.ltb.middle.util.StringReplacer;
import com.cloudbroker.bcs.platform.ltb.middle.util.StringUtil;
import com.cloudbroker.bcs.platform.ltb.middle.util.UpvoteCacheUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by daibd19671 on 2016/11/18.
 */
@Service
public class AskBizServiceImpl implements AskBizService{


    @Resource
    private AskService askService;
    @Resource
    private UserService userService;
    @Resource
    private UserCenterService userCenterService;
    @Resource
    private MsgService msgService;
    @Resource
    private LightinvestingService lightinvestingService;
    @Resource
    private UpvoteRecordService upvoteRecordService;
    @Resource
    private MsgReadRecordService msgReadRecordService;

    @Override
    @Transactional
    public HSBCPSBackVO ask_add(AskAddForm form) {
        if(StringReplacer.hasSensitiveWord(form.getAsk_content(),form.getCompany_id())){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ANSWER_BLACK_WORD_EXIT,HSBCPSBackVO.class);
        }
        Ask ask = new Ask();
        //判断投顾(回答),粉丝(提问)
        if(form.getUser().getUser_type().equals(String.valueOf(UserType.LEADER.getVal()))){
            //回答问题时问题ID验证
            if(StringUtils.isEmpty(form.getQuestion_ask_id())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_ID_ERR,HSBCPSBackVO.class);
            }
            //验证问题是否存在
            Ask temp = new Ask();
            temp.setAsk_id(Long.valueOf(form.getQuestion_ask_id()));
            Ask tempResult = askService.getAsk(temp);
            if(tempResult == null){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_ID_NULL_ERR,HSBCPSBackVO.class);
            }
            if(!tempResult.getCreate_type().equals(AskCreateType.QUESTION.getVal())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_ID_NULL_ERR,HSBCPSBackVO.class);
            }
            //验证投顾是否有权限回复
            if(AskType.ORDINARY.getVal().equals(tempResult.getAsk_type()) && !tempResult.getLeader_id().equals(form.getUser().getUser_id())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ANSWER_USER_ERR,HSBCPSBackVO.class);
            }
            if(AskType.SQUARE.getVal().equals(tempResult.getAsk_type())
                && form.getIs_public().equals(AskPublicType.PRIVATE.getVal())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ANSWER_PUBLIC_ERR,HSBCPSBackVO.class);
            }
            //验证是否已经回答
            temp = new Ask();
            temp.setAnswer_id(Long.valueOf(form.getQuestion_ask_id()));
            temp.setLeader_id(form.getUser().getUser_id());
            Ask answerResult = askService.getAsk(temp);
            if(answerResult!=null){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ANSWER_REPEAT_ERR,HSBCPSBackVO.class);
            }
            //回答
            ask.setCreate_type(AskCreateType.ANSWER.getVal());
            ask.setUser_id(tempResult.getUser_id());
            ask.setLeader_id(Long.valueOf(form.getUser().getUser_id()));
            if(form.getQuestion_ask_id()!=null){
                ask.setAnswer_id(Long.valueOf(form.getQuestion_ask_id()));
            }
            //记录最后回答时间
            tempResult.setUpdate_time(new Date().getTime());
            //如果是非公开回答  则修改问题为非公开
            if(form.getIs_public().equals(AskPublicType.PRIVATE.getVal())
                    && tempResult.getAsk_type().equals(AskType.ORDINARY.getVal())){
                tempResult.setIs_public(AskPublicType.PRIVATE.getVal());
            }
            askService.updateAsk(tempResult);
            //消息
            Msg msg = new Msg();
            msg.setCompany_id(form.getCompany_id());
            msg.setUser_id(tempResult.getUser_id());
            msg.setMsg_type(MsgType.ASK.getVal());
            msg.setCreate_time(new Date().getTime());
            String alias_name = new String("");
            UsersQueryVo usersQueryVo = userCenterService.func_users_query(form.getUser().getUser_id().toString());
            if(VOUtil.isSuccess(usersQueryVo) && usersQueryVo.getData_list()!=null && usersQueryVo.getData_list().size()>0){
                alias_name = StringUtil.replaceMobile(usersQueryVo.getData_list().get(0).getAlias_name());
            }
            msg.setMsg_content(alias_name+"回答了您的问题："+form.getAsk_content());
            msg.setMsg_title("");
            msgService.save(msg);
            if(tempResult.getAsk_type().equals(AskType.ORDINARY.getVal())
                    &&tempResult.getIs_public().equals(AskPublicType.PUBLIC.getVal())){
                UserEntity leader = userService.get(String.valueOf(form.getUser().getUser_id()));
                if(leader!=null){
                    userService.updateAnswerNum(leader);
                }
            }
        }else{
//            if(AskCacheUtil.getAskNum(form.getUser().getUser_id()) >= 2){
//                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ASK_NUM_ERR,HSBCPSBackVO.class);
//            }
//            if(form.getAsk_type().equals(AskType.SQUARE.getVal())
//                    && form.getIs_public().equals(AskPublicType.PRIVATE.getVal())){
//                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTION_PUBLIC_ERR,HSBCPSBackVO.class);
//            }
            if(StringUtils.isEmpty(form.getAsk_type())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_ASK_TYPE_EMPTY,HSBCPSBackVO.class);
            }
            if (!form.getAsk_type().equals(AskType.ORDINARY.getVal())
                    && !form.getAsk_type().equals(AskType.SQUARE.getVal())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_ASK_TYPE_ERR,HSBCPSBackVO.class);
            }
            if(!AskAnonymousType.PUBLIC.getVal().equals(form.getIs_anonymous())
                    && !AskAnonymousType.ANONYMOUS.getVal().equals(form.getIs_anonymous())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.PUBLIC_TYPE_ERR,HSBCPSBackVO.class);
            }
            if(!AskPublicType.PUBLIC.getVal().equals(form.getIs_public())
                    && !AskPublicType.PRIVATE.getVal().equals(form.getIs_public())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ANONYMOUS_TYPE_ERR,HSBCPSBackVO.class);
            }
            if(form.getAsk_type().equals(AskType.ORDINARY.getVal())){
                if(StringUtils.isEmpty(form.getAsk_user_id())){
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_USER_ID_ERR,HSBCPSBackVO.class);
                }
                UserEntity user = new UserEntity();
                user.setUser_id(Long.valueOf(form.getAsk_user_id()));
                UserEntity userEntity = userService.getUserEntity(user);
                if(userEntity == null){
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT, LeaderBackVo.class);
                }
                //提问目标用户类型判断
                if(!userEntity.getUser_type().equals(String.valueOf(UserType.LEADER.getVal()))){
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_USER_ID_ERR,HSBCPSBackVO.class);
                }
                ask.setLeader_id(Long.valueOf(form.getAsk_user_id()));
            }
            //提问
            ask.setCreate_type(AskCreateType.QUESTION.getVal());
            ask.setUser_id(form.getUser().getUser_id());
            ask.setAsk_type(form.getAsk_type());
            AskCacheUtil.addAskNum(form.getUser().getUser_id());
        }
        ask.setAsk_content(form.getAsk_content());
        ask.setCompany_id(form.getCompany_id());
        ask.setSendercomp_id(form.getSendercomp_id());
        ask.setView_flag("0");
        ask.setCreate_time(new Date().getTime());
        ask.setIs_public(form.getIs_public());
        ask.setIs_anonymous(form.getIs_anonymous());
        ask.setProd_code_list(form.getProd_code_list());
        ask.setUpvote_num(0L);
        askService.askAdd(ask);
        return VOUtil.setSuccessResult(new HSBCPSBackVO());
    }

    @Override
    public AskListQryBack ask_list_qry(AskListQryForm form) {
        AskParam param = new AskParam();
        param.setCompany_id(form.getCompany_id());
        param.setQuery_type(form.getQuery_type());
        Pagination pagination = new Pagination();
        pagination.setPage_no(form.getPage_no());
        pagination.setStart_index(form.getStart_row());
        pagination.setPage_size(form.getRequest_num());
        param.setPage(pagination);
        //提问列表
        List<Ask> questionList = new ArrayList<>();
        //回答列表
        List<Ask> answerList = new ArrayList<>();
        param.setCreate_type(AskCreateType.QUESTION.getVal());
        if(form.getQuery_type().equals(AskQryType.ALL_ASK.getVal())){
            param.setIs_public(AskPublicType.PUBLIC.getVal());
        }else if(form.getQuery_type().equals(AskQryType.NEW_ASK.getVal())){
            if(form.getUser()==null){
                return VOUtil.genErrorResult(BasicErrorCodes.NOT_LOGGED, "未登录或已超时",AskListQryBack.class);
            }
            param.setUser_id(form.getUser().getUser_id());
            this.recordMsgReadTime(form.getUser().getUser_id(),MsgType.ASK.getVal(),form.getCompany_id());
        }else if(form.getQuery_type().equals(AskQryType.ANSWER_ASK.getVal())){
            if(form.getUser()==null){
                return VOUtil.genErrorResult(BasicErrorCodes.NOT_LOGGED, "未登录或已超时",AskListQryBack.class);
            }
            param.setUser_id(form.getUser().getUser_id());
            this.recordMsgReadTime(form.getUser().getUser_id(),MsgType.ASK.getVal(),form.getCompany_id());
        }else{
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ASK_QUERY_TYPE_ERR,AskListQryBack.class);
        }
        //统计总数
        int count = askService.countAsk(param);
        //查询提问列表
        questionList = askService.qryAsk(param);
        List<Long> questionIdList = new ArrayList<>(questionList.size());
        for(Ask ask : questionList){
            questionIdList.add(ask.getAsk_id());
        }
        Map<Long,Ask> answerMap = new HashMap<>();
        //查询回答列表
        if(questionList != null && questionList.size() > 0) {
            answerList = askService.qryByAsnwerId(questionIdList);
            for(Ask ask : answerList){
                answerMap.put(ask.getAnswer_id(),ask);
            }
        }
        List<AskView> askViewList = new ArrayList<>();
        for(Ask ask : questionList){
            AskView askView = new AskView();
            askView.setIs_public(ask.getIs_public());
            askView.setQuestion_ask_content(ask.getAsk_content());
            askView.setQuestion_ask_id(ask.getAsk_id());
            askView.setQuestion_create_time(ask.getCreate_time());
            askView.setQuestion_prod_code_list(ask.getProd_code_list());
            askView.setQuestion_anonymous_flag(ask.getIs_anonymous());
            askView.setAsk_type(ask.getAsk_type());

            if(ask.getIs_anonymous().equals(AskAnonymousType.PUBLIC.getVal())){
                askView.setQuestion_company_id(ask.getCompany_id());
                askView.setQuestion_create_type(ask.getCreate_type());
                askView.setQuestion_user_id(ask.getUser_id());
                askView.setQuestion_sendercomp_id(ask.getSendercomp_id());
                askView.setQuestion_view_flag(ask.getView_flag());
            }
            Ask answer = answerMap.get(ask.getAsk_id());
            if(answer != null){
                askView.setQuestion_leader_id(answer.getLeader_id());
                askView.setAnswer_ask_content(answer.getAsk_content());
                askView.setAnswer_ask_id(answer.getAsk_id());
                askView.setAnswer_create_time(answer.getCreate_time());
                askView.setAnswer_prod_code_list(answer.getProd_code_list());
                askView.setAnswer_anonymous_flag(answer.getIs_anonymous());
                askView.setAnswer_upvote_num(answer.getUpvote_num());
                askView.setAnswer_leader_id(answer.getLeader_id());
                if(answer.getIs_anonymous().equals(AskAnonymousType.PUBLIC.getVal())) {
                    askView.setAnswer_company_id(answer.getCompany_id());
                    askView.setAnswer_create_type(answer.getCreate_type());
                    askView.setAnswer_sendercomp_id(answer.getSendercomp_id());
                    askView.setAnswer_user_id(answer.getUser_id());
                    askView.setAnswer_view_flag(answer.getView_flag());
                }
            }
            askViewList.add(askView);
        }
        Map<Long,String> adviserTypeMap = new HashMap<>();
        List<Long> idList = new ArrayList<>();
        for(AskView view : askViewList){
            if(!idList.contains(view.getQuestion_user_id())){
                idList.add(view.getQuestion_user_id());
            }
            if(!idList.contains(view.getQuestion_leader_id())){
                idList.add(view.getQuestion_leader_id());
                InterestDetailForm ledT2Form = new InterestDetailForm();
                ledT2Form.setSendercomp_id(form.getSendercomp_id());
                ledT2Form.setUser_id(String.valueOf(view.getQuestion_leader_id()));
                ledT2Form.setUser_token(form.getUser_token());
                InterestDetailVo interestDetailVo = lightinvestingService.func_interest_detail_query(ledT2Form);
//                InterestDetailVo interestDetailVo = new InterestDetailVo();
                adviserTypeMap.put(view.getQuestion_leader_id(), interestDetailVo.getAdviser_type());
            }
        }
        if(idList==null || idList.size()==0){
            return VOUtil.setSuccessResult(new AskListQryBack());
        }
        //头像、投顾类型
        Map<Long,UserEntityVO> map = this.leaderAvatarMap(idList);
        List<AskListQryBackData> backList = new ArrayList<>(askViewList.size());
        for(AskView a : askViewList){
            AskListQryBackData data = new AskListQryBackData();
            BeanUtils.copyProperties(a,data);
            UserEntityVO leader = map.get(a.getAnswer_leader_id());
            UserEntityVO user = map.get(a.getQuestion_user_id());
            if(leader!=null){
                data.setLeader_avatar(leader.getAvatar());
                data.setLeader_alias_name(leader.getAlias_name());
            }
            if(user!=null){
                data.setUser_avatar(user.getAvatar());
                data.setUser_alias_name(user.getAlias_name());
            }
            data.setAdviser_type(adviserTypeMap.get(a.getQuestion_leader_id()));
            backList.add(data);
        }
        AskListQryBack back = new AskListQryBack();
        back.setCount(count);
        back.setData_list(backList);
        return VOUtil.setSuccessResult(back);
    }


    @Override
    public HSBCPSBackVO ask_remove(AskRemoveForm form) {
        if(!form.getUser().getUser_type().equals(String.valueOf(UserType.LEADER.getVal()))){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.REMOVE_ASK_USER_TYPE_ERR,HSBCPSBackVO.class);
        }
        Ask temp = new Ask();
        temp.setAsk_id(form.getQuestion_ask_id());
        Ask ask = askService.getAsk(temp);
        if(ask==null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_ID_NULL_ERR,HSBCPSBackVO.class);
        }
        if(ask.getLeader_id()!=null && !ask.getLeader_id().equals(form.getUser().getUser_id())){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.REMOVE_ASK_USER_ERR,HSBCPSBackVO.class);
        }
        askService.removeAsk(ask);
        return VOUtil.setSuccessResult(new HSBCPSBackVO());
    }

    @Override
    public AskDetailBack ask_detail(AskDetailForm form) {
        Ask temp = new Ask();
        temp.setAsk_id(form.getQuestion_ask_id());
        Ask ask = askService.getAsk(temp);
        if(ask == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ASK_EMPTY,AskDetailBack.class);
        }
        if(ask.getCreate_type().equals(AskCreateType.ANSWER.getVal())){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ASK_EMPTY,AskDetailBack.class);
        }
        Pagination page = new Pagination();
        page.setPage_no(form.getPage_no());
        page.setStart_index(form.getStart_row());
        page.setPage_size(form.getRequest_num());
        Ask answerQry = new Ask();
        answerQry.setAnswer_id(ask.getAsk_id());
        answerQry.setPage(page);
        List<Ask> answerList = askService.qryByAskId(answerQry);
        //查询头像、昵称
        List<Long> userIdList = new ArrayList<>();
        userIdList.add(ask.getUser_id());
        for(Ask tempAsk : answerList){
            userIdList.add(tempAsk.getLeader_id());
        }
        Map<Long,UserEntityVO> avatarMap = this.leaderAvatarMap(userIdList);
        Map<Long,UserEntity> userEntityMap = this.userQryByIdList(userIdList);
        List<AskDetailBackData> backList = new ArrayList<>();
        //问题详情
        AskDetailBackData askBack = new AskDetailBackData();
        askBack.setAsk_id(ask.getAsk_id());
        askBack.setAsk_content(ask.getAsk_content());
        askBack.setAsk_type(ask.getAsk_type());
        askBack.setAsk_create_type(ask.getCreate_type());
        askBack.setCreate_time(ask.getCreate_time());
        askBack.setIs_anonymous(ask.getIs_anonymous());
        askBack.setIs_public(ask.getIs_public());
        askBack.setProd_code_list(ask.getProd_code_list());
        if(AskAnonymousType.PUBLIC.getVal().equals(ask.getIs_anonymous())){
            askBack.setUser_id(ask.getUser_id());
            UserEntityVO askUserEntity = avatarMap.get(ask.getUser_id());
            if(askUserEntity!=null){
                askBack.setAlias_name(askUserEntity.getAlias_name());
                askBack.setAvatar(askUserEntity.getAvatar());
            }
        }
        backList.add(askBack);
        //回答列表
        for(Ask answer : answerList){
            AskDetailBackData answerBack = new AskDetailBackData();
            answerBack.setAsk_id(answer.getAsk_id());
            answerBack.setAsk_content(answer.getAsk_content());
            answerBack.setAsk_type(answer.getAsk_type());
            answerBack.setAsk_create_type(answer.getCreate_type());
            answerBack.setCreate_time(answer.getCreate_time());
            answerBack.setIs_anonymous(answer.getIs_anonymous());
            answerBack.setIs_public(answer.getIs_public());
            answerBack.setProd_code_list(answer.getProd_code_list());
            answerBack.setUpvote_num(answer.getUpvote_num());
            answerBack.setUser_id(answer.getLeader_id());
            answerBack.setProd_code_list(answer.getProd_code_list());
            if(form.getUser()!=null){
                boolean isUpvoteBool = UpvoteCacheUtil.isUpvoteAsk(answer.getAsk_id(), form.getUser().getUser_id());
                String is_upvote = isUpvoteBool ? "1" : "0";
                answerBack.setIs_upvote(is_upvote);
            }else {
                answerBack.setIs_upvote("0");
            }
            UserEntity userEntity = userEntityMap.get(answer.getLeader_id());
            if(userEntity!=null){
                answerBack.setAnswer_count(userEntity.getAnswer_num());
            }
            UserEntityVO userEntityVO = avatarMap.get(answer.getLeader_id());
            if(userEntityVO!=null){
                answerBack.setAlias_name(userEntityVO.getAlias_name());
                answerBack.setAvatar(userEntityVO.getAvatar());
            }
            InterestDetailForm ledT2Form = new InterestDetailForm();
            ledT2Form.setSendercomp_id(form.getSendercomp_id());
            ledT2Form.setUser_id(String.valueOf(answer.getLeader_id()));
            ledT2Form.setUser_token(form.getUser_token());
            InterestDetailVo detailVo = lightinvestingService.func_interest_detail_query(ledT2Form);
            if(VOUtil.isSuccess(detailVo) && detailVo!=null){
                answerBack.setAdviser_type(detailVo.getAdviser_type());
                answerBack.setClient_branch_no(detailVo.getClient_branch_no());
                answerBack.setBranch_name(detailVo.getBranch_name());
            }
            backList.add(answerBack);
        }
        AskDetailBack askDetailBack = new AskDetailBack();
        askDetailBack.setCount(askService.countAnswer(answerQry));
        askDetailBack.setData_list(backList);
        return VOUtil.setSuccessResult(askDetailBack);
    }


    @Override
    @Transactional
    public HSBCPSBackVO ask_upvote(AskUpvoteForm form) {
        Ask temp = new Ask();
        temp.setAsk_id(form.getAsk_id());
        Ask ask = askService.getAsk(temp);
        if(ask == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ASK_EMPTY,AskDetailBack.class);
        }
        //是否点过赞
        if (UpvoteCacheUtil.isUpvoteAsk(ask.getAsk_id(),form.getUser().getUser_id())){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ASK_UPVOTE_ERR,
                    HSBCPSBackVO.class);
        }
        //数据库同步
        UpvoteRecord upvoteRecord = new UpvoteRecord();
        upvoteRecord.setCompany_id(ask.getCompany_id());
        upvoteRecord.setUser_id(form.getUser().getUser_id());
        upvoteRecord.setUpvote_target_id(ask.getAsk_id());
        upvoteRecord.setUpvote_type(String.valueOf(UpvoteType.ASK_UPVOTE.getVal()));
        upvoteRecord.setCreate_date(System.currentTimeMillis());
        upvoteRecordService.save(upvoteRecord);
        ask.setUpvote_num(ask.getUpvote_num()+1);
        askService.updateAsk(ask);
        UpvoteCacheUtil.addAskUpvoteRecord(ask.getAsk_id(),form.getUser().getUser_id());
        return VOUtil.setSuccessResult(new HSBCPSBackVO());
    }

    @Override
    public AskSearchBack ask_search(AskSearchForm form) {
        AskParam param = new AskParam();
        param.setAsk_content(form.getAsk_content());
        Pagination pagination = new Pagination();
        pagination.setPage_no(form.getPage_no());
        pagination.setStart_index(form.getStart_row());
        pagination.setPage_size(form.getRequest_num());
        param.setPage(pagination);
        param.setIs_public(AskPublicType.PUBLIC.getVal());
        param.setCreate_type(AskCreateType.QUESTION.getVal());
        param.setQuery_type(AskQryType.ANSWER_ASK.getVal());
        List<Ask> searchList = askService.qryAsk(param);
        int count = askService.countAsk(param);
        List<Long> questionList = new ArrayList<>();
        for (Ask ask : searchList) {
            questionList.add(ask.getAsk_id());
        }
        Map<Long,Ask> answerMap = new HashMap<>();
        //根据搜索的问题查询回答列表
        List<Ask> qryByAnswerIdList = new ArrayList<>();
        if(questionList!=null && questionList.size()>0){
            qryByAnswerIdList = askService.qryByAsnwerId(questionList);
        }
        for(Ask ask : qryByAnswerIdList){
            answerMap.put(ask.getAnswer_id(),ask);
        }
        List<AskView> askViewList = new ArrayList<>();
        //组装数据
        for (Ask ask : searchList) {
            AskView askView = new AskView();
            askView.setIs_public(ask.getIs_public());
            askView.setQuestion_ask_content(ask.getAsk_content());
            askView.setQuestion_ask_id(ask.getAsk_id());
            askView.setQuestion_create_time(ask.getCreate_time());
            askView.setQuestion_prod_code_list(ask.getProd_code_list());
            askView.setQuestion_anonymous_flag(ask.getIs_anonymous());
            if (ask.getIs_anonymous().equals(AskAnonymousType.PUBLIC.getVal())) {
                askView.setQuestion_company_id(ask.getCompany_id());
                askView.setQuestion_create_type(ask.getCreate_type());
                askView.setQuestion_user_id(ask.getUser_id());
                askView.setQuestion_sendercomp_id(ask.getSendercomp_id());
                askView.setQuestion_view_flag(ask.getView_flag());
            }
            Ask answer = answerMap.get(ask.getAsk_id());
            if (answer != null) {
                askView.setQuestion_leader_id(answer.getLeader_id());
                askView.setAnswer_ask_content(answer.getAsk_content());
                askView.setAnswer_ask_id(answer.getAsk_id());
                askView.setAnswer_create_time(answer.getCreate_time());
                askView.setAnswer_prod_code_list(answer.getProd_code_list());
                askView.setAnswer_anonymous_flag(answer.getIs_anonymous());
                if (answer.getIs_anonymous().equals(AskAnonymousType.PUBLIC.getVal())) {
                    askView.setAnswer_company_id(answer.getCompany_id());
                    askView.setAnswer_create_type(answer.getCreate_type());
                    askView.setAnswer_leader_id(answer.getLeader_id());
                    askView.setAnswer_sendercomp_id(answer.getSendercomp_id());
                    askView.setAnswer_user_id(answer.getUser_id());
                    askView.setAnswer_view_flag(answer.getView_flag());
                }
            }
            askViewList.add(askView);
        }
        Map<Long,String> adviserTypeMap = new HashMap<>();
        List<Long> idList = new ArrayList<>();
        for(AskView view : askViewList){
            if(!idList.contains(view.getQuestion_user_id())){
                idList.add(view.getQuestion_user_id());
            }
            if(!idList.contains(view.getQuestion_leader_id())){
                idList.add(view.getQuestion_leader_id());
                InterestDetailForm ledT2Form = new InterestDetailForm();
                ledT2Form.setSendercomp_id(form.getSendercomp_id());
                ledT2Form.setUser_id(String.valueOf(view.getQuestion_leader_id()));
                ledT2Form.setUser_token(form.getUser_token());
                InterestDetailVo interestDetailVo = lightinvestingService.func_interest_detail_query(ledT2Form);
//                InterestDetailVo interestDetailVo = new InterestDetailVo();
                adviserTypeMap.put(view.getQuestion_leader_id(), interestDetailVo.getAdviser_type());
            }
        }
        if(idList==null || idList.size()==0){
            return VOUtil.setSuccessResult(new AskSearchBack());
        }
        //头像、投顾类型
        Map<Long,UserEntityVO> map = this.leaderAvatarMap(idList);
        List<AskSearchBackData> backList = new ArrayList<>(askViewList.size());
        for(AskView a : askViewList){
            AskSearchBackData data = new AskSearchBackData();
            BeanUtils.copyProperties(a,data);
            UserEntityVO leader = map.get(a.getQuestion_leader_id());
            UserEntityVO user = map.get(a.getQuestion_user_id());
            if(leader!=null){
                data.setLeader_avatar(leader.getAvatar());
                data.setLeader_alias_name(leader.getAlias_name());
            }
            if(user!=null){
                data.setUser_avatar(user.getAvatar());
                data.setUser_alias_name(user.getAlias_name());
            }
            data.setAdviser_type(adviserTypeMap.get(a.getQuestion_leader_id()));
            backList.add(data);
        }
        AskSearchBack back = new AskSearchBack();
        back.setCount(count);
        back.setData_list(backList);
        return VOUtil.setSuccessResult(back);
    }

    @Override
    public AskFreeBack ask_free(AskFreeForm form) {
        int num = AskCacheUtil.getAskNum(form.getUser().getUser_id());
        AskFreeBack askFreeBack = new AskFreeBack();
        askFreeBack.setAsk_free_num(2 - num);
        return VOUtil.setSuccessResult(askFreeBack);
    }

    private Map<Long,UserEntityVO> leaderAvatarMap(List<Long> list){
        UsersQueryVo usersQueryVo = userCenterService.func_users_query(org.apache.commons.lang3.StringUtils.join(list, ","));
        //查询结果集转成map
        List<UserEntityVO> userList = usersQueryVo.getData_list();
        Map<Long,UserEntityVO> map = new HashMap<>(userList.size());
        for(UserEntityVO user : userList){
            user.setAlias_name(StringUtil.replaceMobile(user.getAlias_name()));//修改单号M201701170424
            map.put(user.getUser_id(),user);
        }
        return map;
    }

    private Map<Long,UserEntity> userQryByIdList(List<Long> list){
        List<UserEntity>  userList = userService.getUserList(list);
        Map<Long,UserEntity> map = new HashMap<>(userList.size());
        for(UserEntity user : userList){
            user.setAlias_name(StringUtil.replaceMobile(user.getAlias_name()));
            map.put(user.getUser_id(),user);
        }
        return map;
    }



    /**
     * 记录消息阅读时间
     * @param user_id
     * @param msgType
     */
    @Transactional
    private void recordMsgReadTime(long user_id,int msgType,String company_id){
        MsgReadRecord temp = new MsgReadRecord();
        temp.setCompany_id(company_id);
        temp.setUser_id(user_id);
        temp.setMsg_type(msgType);
        MsgReadRecord mrr = msgReadRecordService.getByEntity(temp);
        if(mrr == null){
            temp.setRead_time(new Date().getTime());
            msgReadRecordService.save(temp);
        }else{
            mrr.setRead_time(new Date().getTime());
            msgReadRecordService.update(mrr);
        }
    }




    @Override
    public AskListQryBack get_leader_ask(LeaderAsk form) {
        LeaderAskParam param = new LeaderAskParam();
        param.setCompany_id(form.getCompany_id());
        Pagination pagination = new Pagination();
        pagination.setPage_no(form.getPage_no());
        pagination.setStart_index(form.getStart_row());
        pagination.setPage_size(form.getRequest_num());
        param.setPage(pagination);
        param.setQuery_type(AskQryType.ANSWER_ASK.getVal());
        param.setCreate_type(AskCreateType.QUESTION.getVal());
        param.setAsk_type(AskType.ORDINARY.getVal());
        param.setIs_public(AskPublicType.PUBLIC.getVal());
        param.setLeader_id(form.getLeader_id());
        //查询投顾回答列表
        AskParam leaderAskParam = new AskParam();
        leaderAskParam.setCompany_id(form.getCompany_id());
        leaderAskParam.setLeader_id(form.getLeader_id());
        leaderAskParam.setCreate_type(AskCreateType.ANSWER.getVal());
        List<Ask> leaderAnswerList = askService.qryAsk(leaderAskParam);
        List<Long> leaderAnswerIDList = new ArrayList<>();
        for(Ask ask : leaderAnswerList){
            leaderAnswerIDList.add(ask.getAnswer_id());
        }
        param.setList(leaderAnswerIDList);
        //统计总数
        int count = askService.leaderCountAsk(param);
        //查询提问列表
        List<Ask> questionList =  askService.leaderQryAsk(param);
        List<Long> questionIdList = new ArrayList<>();
        for(Ask q : questionList){
            questionIdList.add(q.getAsk_id());
        }
        Map<Long,Ask> answerMap = new HashMap<>();
        //根据questionList查询回答
        if(questionList != null && questionList.size() > 0) {
            List<Ask> answerList = askService.qryByAsnwerId(questionIdList);
            for(Ask ask : answerList){
                answerMap.put(ask.getAnswer_id(),ask);
            }
        }
        List<AskView> askViewList = new ArrayList<>();
        for(Ask ask : questionList){
            AskView askView = new AskView();
            askView.setIs_public(ask.getIs_public());
            askView.setQuestion_ask_content(ask.getAsk_content());
            askView.setQuestion_ask_id(ask.getAsk_id());
            askView.setQuestion_create_time(ask.getCreate_time());
            askView.setQuestion_prod_code_list(ask.getProd_code_list());
            askView.setQuestion_anonymous_flag(ask.getIs_anonymous());
            askView.setAsk_type(ask.getAsk_type());
            if(ask.getIs_anonymous().equals(AskAnonymousType.PUBLIC.getVal())){
                askView.setQuestion_company_id(ask.getCompany_id());
                askView.setQuestion_create_type(ask.getCreate_type());
                askView.setQuestion_user_id(ask.getUser_id());
                askView.setQuestion_sendercomp_id(ask.getSendercomp_id());
                askView.setQuestion_view_flag(ask.getView_flag());
            }
            Ask answer = answerMap.get(ask.getAsk_id());
            if(answer != null){
                askView.setQuestion_leader_id(answer.getLeader_id());
                askView.setAnswer_ask_content(answer.getAsk_content());
                askView.setAnswer_ask_id(answer.getAsk_id());
                askView.setAnswer_create_time(answer.getCreate_time());
                askView.setAnswer_prod_code_list(answer.getProd_code_list());
                askView.setAnswer_anonymous_flag(answer.getIs_anonymous());
                askView.setAnswer_upvote_num(answer.getUpvote_num());
                if(answer.getIs_anonymous().equals(AskAnonymousType.PUBLIC.getVal())) {
                    askView.setAnswer_company_id(answer.getCompany_id());
                    askView.setAnswer_create_type(answer.getCreate_type());
                    askView.setAnswer_leader_id(answer.getLeader_id());
                    askView.setAnswer_sendercomp_id(answer.getSendercomp_id());
                    askView.setAnswer_user_id(answer.getUser_id());
                    askView.setAnswer_view_flag(answer.getView_flag());
                }
            }
            askViewList.add(askView);
        }
        Map<Long,String> adviserTypeMap = new HashMap<>();
        List<Long> idList = new ArrayList<>();
        for(AskView view : askViewList){
            if(!idList.contains(view.getQuestion_user_id())){
                idList.add(view.getQuestion_user_id());
            }
            if(!idList.contains(view.getQuestion_leader_id())){
                idList.add(view.getQuestion_leader_id());
                InterestDetailForm ledT2Form = new InterestDetailForm();
                ledT2Form.setSendercomp_id(form.getSendercomp_id());
                ledT2Form.setUser_id(String.valueOf(view.getQuestion_leader_id()));
                ledT2Form.setUser_token(form.getUser_token());
                InterestDetailVo interestDetailVo = lightinvestingService.func_interest_detail_query(ledT2Form);
//                InterestDetailVo interestDetailVo = new InterestDetailVo();
                adviserTypeMap.put(view.getQuestion_leader_id(), interestDetailVo.getAdviser_type());
            }
        }
        if(idList==null || idList.size()==0){
            return VOUtil.setSuccessResult(new AskListQryBack());
        }
        //头像、投顾类型
        Map<Long,UserEntityVO> map = this.leaderAvatarMap(idList);
        List<AskListQryBackData> backList = new ArrayList<>(askViewList.size());
        for(AskView a : askViewList){
            AskListQryBackData data = new AskListQryBackData();
            BeanUtils.copyProperties(a,data);
            UserEntityVO leader = map.get(a.getQuestion_leader_id());
            UserEntityVO user = map.get(a.getQuestion_user_id());
            if(leader!=null){
                data.setLeader_avatar(leader.getAvatar());
                data.setLeader_alias_name(leader.getAlias_name());
            }
            if(user!=null){
                data.setUser_avatar(user.getAvatar());
                data.setUser_alias_name(user.getAlias_name());
            }
            data.setAdviser_type(adviserTypeMap.get(a.getQuestion_leader_id()));
            backList.add(data);
        }
        AskListQryBack back = new AskListQryBack();
        back.setCount(count);
        back.setData_list(backList);
        return VOUtil.setSuccessResult(back);
    }


    @Override
    public AskListQryBack leader_ask_list_qry(AskListQryForm form) {
        LeaderAskParam param = new LeaderAskParam();
        param.setCompany_id(form.getCompany_id());
        param.setQuery_type(form.getQuery_type());
        Pagination pagination = new Pagination();
        pagination.setPage_no(form.getPage_no());
        pagination.setStart_index(form.getStart_row());
        pagination.setPage_size(form.getRequest_num());
        param.setPage(pagination);
        //提问列表
        List<Ask> questionList = new ArrayList<>();
        //回答列表
        List<Ask> answerList = new ArrayList<>();
        param.setCreate_type(AskCreateType.QUESTION.getVal());
        if(form.getQuery_type().equals(AskQryType.NEW_ASK.getVal())){
            if (StringUtils.isNotEmpty(form.getAsk_type())
                    && !form.getAsk_type().equals(AskType.ORDINARY.getVal())
                    && !form.getAsk_type().equals(AskType.SQUARE.getVal())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_ASK_TYPE_ERR,AskListQryBack.class);
            }
            if(StringUtils.isNotEmpty(form.getAsk_type())){
                param.setAsk_type(form.getAsk_type());
            }
            param.setRemove_flag(AskRemoveType.NOREMOVE.getVal());
            param.setLeader_id(form.getUser().getUser_id());
        }else if(form.getQuery_type().equals(AskQryType.ANSWER_ASK.getVal())){
            param.setUser_type(form.getUser().getUser_type());
            if (StringUtils.isNotEmpty(form.getAsk_type())
                    && !form.getAsk_type().equals(AskType.ORDINARY.getVal())
                    && !form.getAsk_type().equals(AskType.SQUARE.getVal())){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.QUESTOIN_ASK_TYPE_ERR,AskListQryBack.class);
            }
            if(StringUtils.isNotEmpty(form.getAsk_type())){
                param.setAsk_type(form.getAsk_type());
            }
            param.setRemove_flag(AskRemoveType.NOREMOVE.getVal());
            param.setLeader_id(form.getUser().getUser_id());
        }else{
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AskErrorInfo.ASK_QUERY_TYPE_ERR,AskListQryBack.class);
        }
        //查询投顾回答列表
        AskParam leaderAskParam = new AskParam();
        leaderAskParam.setCompany_id(form.getCompany_id());
        leaderAskParam.setLeader_id(form.getUser().getUser_id());
        leaderAskParam.setCreate_type(AskCreateType.ANSWER.getVal());
        List<Ask> leaderAnswerList = askService.qryAsk(leaderAskParam);
        List<Long> leaderAnswerIDList = new ArrayList<>();
        for(Ask ask : leaderAnswerList){
            leaderAnswerIDList.add(ask.getAnswer_id());
        }
        param.setList(leaderAnswerIDList);
        //统计总数
        int count = askService.leaderCountAsk(param);
        //查询提问列表
        questionList = askService.leaderQryAsk(param);
        List<Long> questionIdList = new ArrayList<>(questionList.size());
        for(Ask ask : questionList){
            questionIdList.add(ask.getAsk_id());
        }
        Map<Long,Ask> answerMap = new HashMap<>();
        //查询回答列表
        if(questionList != null && questionList.size() > 0) {
            answerList = askService.qryByAsnwerId(questionIdList);
            for(Ask ask : answerList){
                answerMap.put(ask.getAnswer_id(),ask);
            }
        }
        List<AskView> askViewList = new ArrayList<>();
        for(Ask ask : questionList){
            AskView askView = new AskView();
            askView.setIs_public(ask.getIs_public());
            askView.setQuestion_ask_content(ask.getAsk_content());
            askView.setQuestion_ask_id(ask.getAsk_id());
            askView.setQuestion_create_time(ask.getCreate_time());
            askView.setQuestion_prod_code_list(ask.getProd_code_list());
            askView.setQuestion_anonymous_flag(ask.getIs_anonymous());
            askView.setAsk_type(ask.getAsk_type());
            if(ask.getIs_anonymous().equals(AskAnonymousType.PUBLIC.getVal())){
                askView.setQuestion_company_id(ask.getCompany_id());
                askView.setQuestion_create_type(ask.getCreate_type());
                askView.setQuestion_user_id(ask.getUser_id());
                askView.setQuestion_sendercomp_id(ask.getSendercomp_id());
                askView.setQuestion_view_flag(ask.getView_flag());
            }
            Ask answer = answerMap.get(ask.getAsk_id());
            if(answer != null){
                askView.setQuestion_leader_id(answer.getLeader_id());
                askView.setAnswer_ask_content(answer.getAsk_content());
                askView.setAnswer_ask_id(answer.getAsk_id());
                askView.setAnswer_create_time(answer.getCreate_time());
                askView.setAnswer_prod_code_list(answer.getProd_code_list());
                askView.setAnswer_anonymous_flag(answer.getIs_anonymous());
                askView.setAnswer_upvote_num(answer.getUpvote_num());
                if(answer.getIs_anonymous().equals(AskAnonymousType.PUBLIC.getVal())) {
                    askView.setAnswer_company_id(answer.getCompany_id());
                    askView.setAnswer_create_type(answer.getCreate_type());
                    askView.setAnswer_leader_id(answer.getLeader_id());
                    askView.setAnswer_sendercomp_id(answer.getSendercomp_id());
                    askView.setAnswer_user_id(answer.getUser_id());
                    askView.setAnswer_view_flag(answer.getView_flag());
                }
            }
            askViewList.add(askView);
        }
        Map<Long,String> adviserTypeMap = new HashMap<>();
        List<Long> idList = new ArrayList<>();
        for(AskView view : askViewList){
            if(!idList.contains(view.getQuestion_user_id())){
                idList.add(view.getQuestion_user_id());
            }
            if(!idList.contains(view.getQuestion_leader_id())){
                idList.add(view.getQuestion_leader_id());
                InterestDetailForm ledT2Form = new InterestDetailForm();
                ledT2Form.setSendercomp_id(form.getSendercomp_id());
                ledT2Form.setUser_id(String.valueOf(view.getQuestion_leader_id()));
                ledT2Form.setUser_token(form.getUser_token());
                InterestDetailVo interestDetailVo = lightinvestingService.func_interest_detail_query(ledT2Form);
//                InterestDetailVo interestDetailVo = new InterestDetailVo();
                adviserTypeMap.put(view.getQuestion_leader_id(), interestDetailVo.getAdviser_type());
            }
        }
        if(idList==null || idList.size()==0){
            return VOUtil.setSuccessResult(new AskListQryBack());
        }
        //头像、投顾类型
        Map<Long,UserEntityVO> map = this.leaderAvatarMap(idList);
        List<AskListQryBackData> backList = new ArrayList<>(askViewList.size());
        for(AskView a : askViewList){
            AskListQryBackData data = new AskListQryBackData();
            BeanUtils.copyProperties(a,data);
            UserEntityVO leader = map.get(a.getQuestion_leader_id());
            UserEntityVO user = map.get(a.getQuestion_user_id());
            if(leader!=null){
                data.setLeader_avatar(leader.getAvatar());
                data.setLeader_alias_name(leader.getAlias_name());
            }
            if(user!=null){
                data.setUser_avatar(user.getAvatar());
                data.setUser_alias_name(user.getAlias_name());
            }
            data.setAdviser_type(adviserTypeMap.get(a.getQuestion_leader_id()));
            backList.add(data);
        }
        AskListQryBack back = new AskListQryBack();
        back.setCount(count);
        back.setData_list(backList);
        return VOUtil.setSuccessResult(back);
    }

}
